package com.cjsip.service;


import java.util.Timer;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.sip.SipAudioCall;
import android.net.sip.SipProfile;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import com.example.android.sip.WalkieTalkieActivity;

public class CJService extends Service {
	
	@Override
	public IBinder onBind(Intent intent){
		return new Binder();
	}
	
	private Timer timer = new Timer();
	
	private static final String THIS_FILE = "CJService";
	
	private IncomingCallReceiver receiver;
	
	class IncomingCallReceiver extends BroadcastReceiver {
	    /**
	     * Processes the incoming call, answers it, and hands it over to the
	     * WalkieTalkieActivity.
	     * @param context The context under which the receiver is running.
	     * @param intent The intent being received.
	     */
	    @Override
	    public void onReceive(Context context, Intent intent) {
	        SipAudioCall incomingCall = null;
	        WalkieTalkieActivity wtActivity=null;
	        try {

	            SipAudioCall.Listener listener = new SipAudioCall.Listener() {
	                @Override
	                public void onRinging(SipAudioCall call, SipProfile caller) {
	                    try {
	                        call.answerCall(30);
	                    } catch (Exception e) {
	                        e.printStackTrace();
	                    }
	                }
	            };

	            wtActivity = (WalkieTalkieActivity) context;
	            
	            incomingCall = wtActivity.manager.takeAudioCall(intent, listener);
	            incomingCall.answerCall(30); // FORSE DA MODIFCARE
	            incomingCall.startAudio();
	            incomingCall.setSpeakerMode(true);
	            if(incomingCall.isMuted()) {
	                incomingCall.toggleMute();
	            }

	            wtActivity.call = incomingCall;

	            wtActivity.updateStatus(incomingCall);

	        } catch (Exception e) {
	            if (incomingCall != null) {
	                incomingCall.close();
	            }
	        }
	        finally{
	        	incomingCall.close();
	        	wtActivity = null;
	        }
	    }
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		Log.i(THIS_FILE, "Create SIP Service");
		
	}
	@Override 
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		Log.d(THIS_FILE, "Listen for phone state ");
		receiver = new IncomingCallReceiver();
		
	}
}
